package com.socket.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangg
 * @date 2019/4/12 13:30
 */
public class NIOSocketClient implements Runnable{

    private  String address;
    private  int port;
    private InetSocketAddress remote;

    private SocketChannel channel =null;
    private ByteBuffer buffer = ByteBuffer.allocate(1204*8);

    public NIOSocketClient(String address, int port) {
        this.address = address;
        this.port = port;
        remote = new InetSocketAddress(this.address,this.port);
    }

    public NIOSocketClient(InetSocketAddress remote) {
        this.remote = remote;
    }

    @Override
    public void run() {
        try {
            channel=SocketChannel.open();
            channel.connect(remote);
            Thread th= Thread.currentThread();
            byte[] bs = new byte[buffer.remaining()];
            System.in.read(bs);
            buffer.put(bs);
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 50, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {

                Thread thread= new Thread(r);
                thread.setName("client-"+thread.getId());
                return thread;
            }
        });
        executor.allowCoreThreadTimeOut(true);
        executor.execute(new NIOSocketClient("127.0.0.1",80));
    }
}
